package com.cjd.common.utils

import com.cjd.common.timer.TimeCountDownTimer

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/10/19
 * description
 */
object TimeCountDownUtil {

    private val map: MutableMap<String, TimeCountDownTimer> by lazy {
        mutableMapOf<String, TimeCountDownTimer>()
    }

    fun put(
        key: String, millisInFuture: Long = 60 * 1000,
        countDownInterval: Long = 1000,
        listener: ((residueSecond: Long, isFinished: Boolean) -> Unit)? = null
    ) {
        var timer = map[key]
        if (timer == null) {
            timer = TimeCountDownTimer(millisInFuture, countDownInterval, listener)
            map[key] = timer
            timer.start()
        } else {
            if (timer.isFinished)
                timer.start()
            timer.setCountDownListener(listener)
        }
    }

    fun get(key: String): TimeCountDownTimer? = map[key]

    fun isRunning(key: String): Boolean {
        val timer = map[key]

        return timer != null && !timer.isFinished
    }

    fun remove(key: String) {
        val countDownTimer = map[key]
        countDownTimer?.let {
            if (!it.isFinished)
                it.cancel()
            map.remove(key)
        }
    }
}